package com.sunlee.admin.api.module.oss.cloud.impl;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.region.Region;
import com.sunlee.admin.api.module.oss.cloud.AbstractCloudStorageService;
import com.sunlee.admin.api.module.oss.cloud.CloudStorageConfig;
import io.github.artislong.core.StandardOssClient;
import io.github.artislong.core.tencent.TencentOssClient;
import io.github.artislong.core.tencent.TencentOssProperties;
import io.github.artislong.model.OssInfo;

import java.io.InputStream;

/**
 * 腾讯云存储
 *
 * @author sunlee
 */
public class QCloudCloudStorageService extends AbstractCloudStorageService {

    private TencentOssClient tencentOssClient;

    public QCloudCloudStorageService(CloudStorageConfig config) {
        this.config = config;
        this.init(buildOssClient());
    }

    /**
     * 构建一个TencentiCos客户端
     *
     * @return TencentiCos客户端
     */
    public StandardOssClient buildOssClient() {
        //1、初始化用户身份信息(secretId, secretKey)
        COSCredentials credentials = new BasicCOSCredentials(config.getQcloudSecretId(), config.getQcloudSecretKey());
        //2、设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(config.getQcloudRegion()));
        //3、实例化cos客户端
        COSClient cosClient = new COSClient(credentials, clientConfig);

        tencentOssClient = new TencentOssClient(cosClient, getTencentOssProperties());
        return tencentOssClient;
    }

    private TencentOssProperties getTencentOssProperties() {
        TencentOssProperties tencentOssProperties = new TencentOssProperties();
        tencentOssProperties.setEnable(true);
        tencentOssProperties.setBasePath("/");
        tencentOssProperties.setBucketName(config.getQcloudBucketName());
        return tencentOssProperties;
    }


    @Override
    public OssInfo upLoad(InputStream is, String targetName) {
        OssInfo ossInfo = super.upLoad(is, targetName);
        ossInfo.setPath(config.getQcloudDomain() + ossInfo.getPath());
        return ossInfo;
    }

    @Override
    public void delete(String targetName) {
        super.delete(targetName.replace(config.getQcloudDomain(), ""));
    }

    @Override
    public Boolean isExist(String targetName) {
        return tencentOssClient.isExist(targetName.replace(config.getQcloudDomain(), ""));
    }
}